class SceneEditor extends GuaScene {
    constructor(game) {
        super(game)
        this.items = []

        var paddle = Paddle(game)
        var ball = Ball(game)
        this.items.push(paddle)
        this.items.push(ball)

        this.score = 0
        this.dragedItem = null
        this.blocks = loadLevel(game, 1)
        this.paused = false

        game.registerAction('a', function() {
            self.paddle.moveLeft()
        })
        game.registerAction('d', function() {
            self.paddle.moveRight()
        })
        game.registerAction('f', function() {
            self.ball.fire()
        })
        window.document.getElementById("id-add-block").addEventListener('click', function(event) {
            var b = Block(self.game, [50, 250])
            self.items.push(b)
            self.save()
        })



        var rect = this.game.canvas.getBoundingClientRect()
        this.game.canvas.addEventListener('mousedown', function(event) {
            var x = event.clientX - rect.left
            var y = event.clientY - rect.top
            for (let i = 0; i < self.items.length; i++) {
                const element = self.items[i];
                if (pointInItem(x, y, element)) {
                    self.dragedItem = element
                }

            }
        })
        this.game.canvas.addEventListener('mousemove', function(event) {
            var x = event.clientX - rect.left
            var y = event.clientY - rect.top
            if (self.dragedItem) {
                // log('move')
                self.dragedItem.x = x
                self.dragedItem.y = y
            }
        })
        this.game.canvas.addEventListener('mouseup', function(event) {
            self.dragedItem = null
        })
        window.addEventListener('keydown', function(event) {
            if (event.key == 'Delete') {
                if (self.dragedItem) {
                    for (let i = 0; i < self.items.length; i++) {
                        const element = self.items[i]
                        if (self.dragedItem == element) {
                            self.items.splice(i, 1)
                        }
                    }
                }
            }
        })

    }

    save() {
        var target = window.document.getElementById("id-items-json")
        var json = JSON.stringify(this.items)
        ajax('POST', 'http://localhost:8080/', json, function(json) {
            log('拿到ajax响应')
            var message = json.message
            alert(message)
        })
    }

    draw() {
        for (let i = 0; i < this.items.length; i++) {
            const element = this.items[i];
            this.game.drawImage(element)

        }
        this.game.context.strokeText('分数: ' + this.score, 20, 250)
    }

    update() {

    }

}